#include <stdio.h>
#include <ctype.h>
#include <string.h>

int count_chars(const char *filename)
{
    FILE *file = fopen(filename, "r");
    if (file == NULL)
    {
        printf("Error: File '%s' does not exist or cannot be opened\n", filename);
        return -1;
    }
    int count = 0;
    int c;
    while ((c = fgetc(file)) != EOF)
    {
        if (c != '\n') // Ignore newline characters
            count++;
    }
    fclose(file);
    return count;
}

int count_words(const char *filename)
{
    FILE *file = fopen(filename, "r");
    if (file == NULL)
    {
        printf("Error: File '%s' does not exist or cannot be opened\n", filename);
        return -1;
    }
    int count = 0, in_word = 0;
    int c;
    while ((c = fgetc(file)) != EOF)
    {
        if (isspace(c)) // Ignore spaces and other whitespace characters
        {
            in_word = 0;
        }
        else if (isalnum(c) && !in_word) // Only count alphanumeric sequences as words
        {
            count++;
            in_word = 1;
        }
    }
    fclose(file);
    return count;
}

int count_sentences(const char *filename)
{
    FILE *file = fopen(filename, "r");
    if (file == NULL)
    {
        printf("Error: File '%s' does not exist or cannot be opened\n", filename);
        return -1;
    }
    int count = 0, last_was_end = 0;
    int c;
    while ((c = fgetc(file)) != EOF)
    {
        if (c == '.' || c == '!' || c == '?')
        {
            if (!last_was_end)
            {
                count++;
                last_was_end = 1;
            }
        }
        else
        {
            last_was_end = 0;
        }
    }
    fclose(file);
    return count;
}


int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("Usage: wc.exe [option] [filename]\n");
        printf("Supported options:\n");
        printf("  -c  Count characters\n");
        printf("  -w  Count words\n");
        printf("  -s  Count sentences\n");
        return 1;
    }

    char *option = argv[1];
    char *filename = argv[2];

    if (strcmp(option, "-c") == 0)
    {
        int chars = count_chars(filename);
        if (chars != -1)
            printf("Character count: %d\n", chars);
    }
    else if (strcmp(option, "-w") == 0)
    {
        int words = count_words(filename);
        if (words != -1)
            printf("Word count: %d\n", words);
    }
    else if (strcmp(option, "-s") == 0)
    {
        int sentences = count_sentences(filename);
        if (sentences != -1)
            printf("Sentence count: %d\n", sentences);
    }
    else
    {
        printf("Error: Unknown option '%s'\n", option);
        return 1;
    }

    return 0;
}
